package com.bree.erp.jsf.validator;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import com.bree.erp.entity.User;
import com.bree.erp.service.UserService;

@ManagedBean(name="createUserValidator")
public class CreateUserValidator {

	private UIInput newPassword;

	@EJB
	private UserService userService;

	public void validateLogin(FacesContext context, UIComponent arg1, Object object)
			throws ValidatorException {
		String email = object.toString();
		
		User user = userService.read(email);
		if(user != null) {
			FacesMessage msg = new FacesMessage("Username validation failed.",
					"Email address is already taken!");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg);
		}
	}

	public void validatePassword(FacesContext context, UIComponent arg1, Object object)
			throws ValidatorException {
		String newPass = this.newPassword.getValue().toString();
		String retyped = object.toString();
		
		if(!retyped.equals(newPass)) {
			FacesMessage msg = new FacesMessage("Password validation failed.",
					"Passwords did not matched!");
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg);
		}
	}
	
	/**
	 * @return the newPassword
	 */
	public UIInput getNewPassword() {
		return newPassword;
	}

	/**
	 * @param newPassword the newPassword to set
	 */
	public void setNewPassword(UIInput newPassword) {
		this.newPassword = newPassword;
	}
}
